import os
import json
import typer
from typing import Optional
from intelli_port.commons.config import load_settings
from .registry import ensure_dir, save_metadata


app = typer.Typer()


@app.command()
def run(
    data_dir: Optional[str] = None,
    output_dir: Optional[str] = None,
    sample_rate: int = 16000,
    frame_ms: int = 20,
    epochs: int = 3,
):
    s = load_settings()
    data_dir = data_dir or s.asr_finetune_data_dir
    output_dir = output_dir or s.asr_output_dir
    ensure_dir(output_dir)
    files = [x for x in os.listdir(data_dir) if x.endswith(".wav")]
    cfg = {
        "sample_rate": sample_rate,
        "frame_ms": frame_ms,
        "epochs": epochs,
        "samples": len(files),
        "data_dir": data_dir,
    }
    with open(os.path.join(output_dir, "last_config.json"), "w", encoding="utf-8") as f:
        json.dump(cfg, f, ensure_ascii=False, indent=2)
    save_metadata(output_dir, "asr", "paddlespeech", output_dir, {"samples": len(files)})
    typer.echo(output_dir)


if __name__ == "__main__":
    app()